﻿using System;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;

namespace JH
{
    /// <summary>
    ///  有道词典文本翻译帮助类
    ///  接口文档： https://ai.youdao.com/DOCSIRMA/html/trans/api/wbfy/index.html#section-9
    /// </summary>
    public static class TextTranslationHelper
    {
        /// <summary>
        ///  ID 网站自己申请
        /// </summary>
        private static readonly string AppKey = "57f768c3d72ddfac";

        /// <summary>
        /// 密钥 网站自己申请
        /// </summary>
        private static readonly string AppSecret = "2ddNYTcYgvApGtalmoyXBUzhiLndnHWY";
        
        /// <summary>
        ///  有道词典文本翻译接口地址
        /// </summary>
        private static readonly string Url = "https://openapi.youdao.com/api"; 

        /// <summary>
        ///  翻译为中文
        /// </summary>
        public static async  JTask TranslateToCn(string origin, Action<string> callback)
        {
            await Translate(origin, "zh-CHS", callback);
        }
        
        /// <summary>
        ///  翻译为英文
        /// </summary>
        public static async JTask TranslateToEn(string origin, Action<string> callback)
        {
            await Translate(origin, "en", callback);
        }
        
        /// <summary>
        ///  获取翻译结果
        /// </summary>
        public static async JTask Translate(string origin,string targetLange, Action<string> callback)
        {
            //上传实体类
           var upload = new TextTranslationUpload( origin, AppKey, AppSecret,"auto",targetLange);

           //生成请求
           var request = UnityWebRequest.Post(Url, upload.GetWWWForm());
           
           //发送请求
            await  request.SendWebRequest();
            
            //判断请求是否成功
            if (request.result is UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError($"有道词典文本翻译请求失败！错误信息：{request.error}");
                return;
            }
            
            //获取请求结果
            var result = request.downloadHandler.text;
           // typeof(TextTranslationHelper).SaveTextToTempEM( result, "YouDaoTranslationResult.json");
           
            //解析请求结果
            var translationResult = JsonConvert.DeserializeObject<TextTranslationResult>(result);
            
            //判断是否解析成功
            if (translationResult == null)
            {
                Debug.LogError($"有道词典文本翻译结果解析失败！错误信息：{result}");
                return;
            }
            
            //判断是否翻译成功
            if (translationResult.ErrorCode != "0")
            {
                Debug.LogError($"有道词典文本翻译失败！错误信息：{translationResult.ErrorCode}");
                return;
            }
            
            //获取翻译结果
            var translation = translationResult.Translation[0];
            
            //回调
            callback?.Invoke(translation);
        }
    }
}